package com.zftlive.share.adapterview.base;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import share.zftlive.com.adapterview.R;

/**
 * 多种类型适配器基类
 *
 * @author 曾繁添
 * @version 1.0
 */
public abstract class AbsMutilTypeAdapter extends BasicAdapter {

    /**
     * item模板映射<K=viewType,V=AbsViewTemplet>
     */
    private Map<Integer,Class<? extends AbsViewTemplet> > mViewTemplet = new TreeMap<>();

    /**
     * 日志输出标志
     */
    private final String TAG = this.getClass().getSimpleName();

    public AbsMutilTypeAdapter(Context mContext) {
        super(mContext);
        registeViewTemplet(mViewTemplet);
    }

    @Override
    public int getItemViewType(int position) {
        IAdapterModel model = getItem(position);
        return adjustItemViewType(model, position);
    }

    @Override
    public int getViewTypeCount() {
        //官方要求viewType必须从0索引开始
        int maxViewType = 0;
        for (Iterator<Integer> it = mViewTemplet.keySet().iterator(); it.hasNext();){
            maxViewType = it.next();
        }
        //兼容跨越索引导致的ArrayIndexOutOfBoundsException,但是不推荐,因为会增加listview回收缓存view的数组长度开销
        return (maxViewType >= mViewTemplet.size())?(maxViewType+1):mViewTemplet.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AbsViewTemplet mTemplet = null;
        int viewType = getItemViewType(position);
        if(null == convertView){
            mTemplet = AbsViewTemplet.createViewTemplet(mViewTemplet.get(viewType), getContext());
            mTemplet.inflate(viewType, position, parent);
            mTemplet.initView();
            convertView = mTemplet.getItemLayoutView();
            convertView.setTag(R.id.view_templet, mTemplet);
        }else{
            mTemplet = (AbsViewTemplet)convertView.getTag(R.id.view_templet);
        }

        //填充数据
        IAdapterModel rowData = getItem(position);
        mTemplet.holdCurrentParams(viewType,position,rowData);
        mTemplet.fillData(rowData, position);
        return convertView;
    }

    /**
     * 注册viewType以及绑定的Templet，一定要在listview.setAdapter方法之前调用
     * @param mViewTemplet
     */
    protected abstract void registeViewTemplet(Map<Integer,Class<? extends AbsViewTemplet> > mViewTemplet);

    /**
     * 根据数据模型返回对应的ViewType
     *
     * @param model 数据模型
     * @param position 当前数据位置
     * @return
     */
    protected abstract int adjustItemViewType(IAdapterModel model, int position);
}
